package com.dily.scaffold.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Time:2021/6/12
 * Author: Dily
 * Remark:
 * Excel导出工具
 **/
@Component
public class ExcelUtils {
    /**
     * 根据List<T>生成EXCEL并导出
     *
     * @param response
     * @param fileName
     * @param dataList
     * @param <T>
     * @return
     */
    public static <T> T downloadExcel(HttpServletResponse response, String fileName, List<T> dataList) {
        OutputStream os = null;
        //设置响应头
//        setResponseHeader(response, fileName);
        try {
            //获取输出流
            os = response.getOutputStream();
            //内存中保留1000条数据，以免内存溢出，其余写入硬盘
            SXSSFWorkbook wb = new SXSSFWorkbook(1000);
            //获取该工作区的第一个sheet
            Sheet sheet = wb.createSheet("sheet1");
            Row row = null;
            int columnIndex = 0;

            row = sheet.createRow(0);
            row.setHeight((short) (22.50 * 20));//设置行高

            //EXCEL表添加表头
            Class<?> tClass = dataList.get(0).getClass();
            Field[] fields = tClass.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                row.createCell(i).setCellValue(fields[i].getName());
            }
            //EXCEL表添加数据
            String jsonString = JSON.toJSONString(dataList);
            JSONArray jsonArray = JSON.parseArray(jsonString);
            for (int i = 0; i < dataList.size(); i++) {
                row = sheet.createRow(i + 1);
                columnIndex = 0;
                for (Field field : fields) {
                    String cell = "";
                    if (jsonArray.getJSONObject(i).get(field.getName()) != null) {
                        cell = jsonArray.getJSONObject(i).get(field.getName()).toString();
                    }
                    row.createCell(columnIndex++).setCellValue(cell);
                }
            }
            sheet.setDefaultRowHeight((short) (16.5 * 20));

            //列宽自适应
//            for (int i = 0; i <= 11; i++) {
//                sheet.autoSizeColumn(i);
//            }
            //设置头文件, 文件名
            setResponseHeader(response, fileName);
            //将整理好的excel数据写入流中
            wb.write(os);
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                // 关闭输出流
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
        设置浏览器下载响应头
     */
    private static void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String name = fileName + "_" + simpleDateFormat.format(new Date());
//            fileName = new String(name.getBytes("UTF-8"),"ISO8859-1");
//            fileName = new String(name.getBytes("ISO8859-1"),"UTF-8");
            fileName = new String(name.getBytes("UTF-8"));
//            fileName = new String(name.getBytes("ISO8859-1"));

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream;charset=UTF-8");
//            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment");
            response.setHeader("filename", fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
